package com.oasistudio.tk.connector.imp;

import java.io.UnsupportedEncodingException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import org.json.JSONArray;
import org.json.JSONObject;

import com.oasistudio.tk.connector.TopAPIConnectorHelper;
import com.oasistudio.tk.connector.TopAPIHelper;
import com.oasistudio.tk.connector.TopApiRequest;
import com.oasistudio.tk.connector.TopApiResponse;
import com.taobao.tbw.common.TBWContext;

public class TaobaokeShopsConvertConnector implements TopAPIConnectorHelper {
	private String shopIds;//???10�????d�??,???
	private String fields="user_id,shop_title,click_url,commission_rate,seller_credit,shop_type,total_auction,auction_count";//�??????��????
	
	public TaobaokeShopsConvertConnector(){
	}
	
	public void setShopIds(String shopIds){
		this.shopIds = shopIds;
	}

	public void setFields(String fields){
		this.fields = fields;
	}

	@Override
	public Object asyncPaser(byte[] part) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getApiUrl() {
		TopApiRequest request = new TopApiRequest();
		TreeMap<String, String> params = new TreeMap<String, String>();
		params.put("app_key", TBWContext.getInstance().getAppKey());
		//params.put("app_secret", TBWContext.getInstance().getAppSecret());
		params.put("partner_id", "top-apitools");
		params.put("sign_method", "md5");
		params.put("format", "json");
		params.put("v", "2.0");

		params.put("method", "taobao.taobaoke.shops.convert");
		params.put("timestamp", TopAPIHelper.getTopTimestamp());
		params.put("session", TBWContext.getInstance().getTopsession());
		params.put("pid", TBWContext.getInstance().getPID());
		
		params.put("sids", this.shopIds);
		//params.put("fields", "click_url,num_iid,commission,commission_rate,commission_num,commission_volume,title,price");
		params.put("fields", fields);
		
		request.params = params;
		return request.generalRequestUrl(true);
	}

	/**
	 * �??�?????�???��? total_results Number ??��?��?交�?信�??��? trades Trade[] 交�?信�???��
	 * hash_next Boolean ??��???�?��
	 */
	@Override
	public Object syncPaser(byte[] all) {
		NumberFormat nf = NumberFormat.getInstance();
		nf.setMinimumFractionDigits(2);
		nf.setMaximumFractionDigits(2);
		ShopCommissionInfo commissionInfo = new ShopCommissionInfo();
		try {
			
			TopApiResponse response = new TopApiResponse("taobaoke_shops_convert_response");
			String str = new String(all, "UTF-8");
			//Log.d("return msg:", str);
			if (response.parseResult(str).success) {
				commissionInfo.isSuccess = true;
				JSONObject jsObj = response.data;
				if(jsObj.has("taobaoke_shops")){
					commissionInfo.totalResults = jsObj.optInt("total_results");
					List<ShopCommission> commissions = new ArrayList<ShopCommission>();
					commissionInfo.commissions = commissions;
					JSONArray array = jsObj.optJSONObject("taobaoke_shops").optJSONArray("taobaoke_shop");
					for(int i=0; i<array.length(); i++){
						JSONObject shopJSON = array.getJSONObject(i);
						ShopCommission shop = new ShopCommission();
						shop.auction_count = shopJSON.optInt("auction_count");
						shop.click_url = shopJSON.optString("click_url");
						//commission.commission_rate = commissionJSON.optString("commission_rate");
						String commissionRateString = shopJSON.optString("commission_rate");
						System.out.println("TaobaokeItemsConvertConnector.syncPaser() commissionRateString = "+commissionRateString);
						try{
							double commissionRateDouble = Double.valueOf(commissionRateString);
							shop.commission_rate = nf.format(commissionRateDouble*TBWContext.FINAL_RATE);
							System.out.println("TaobaokeItemsConvertConnector.syncPaser() shop.commission_rate = "+shop.commission_rate);
						}catch(Exception e){
							//e.printStackTrace();
						}
						shop.seller_credit = shopJSON.optString("seller_credit");
						shop.shop_title = shopJSON.optString("shop_title");
						shop.total_auction = shopJSON.optString("total_auction");
						shop.user_id = shopJSON.optLong("user_id");
						shop.shop_type = shopJSON.optString("shop_type");
						
						commissions.add(shop);
					}
				}
			} else {
				commissionInfo.isSuccess = false;
				commissionInfo.errCode = response.errCode;
				commissionInfo.errInfo = response.errInfo;
			}

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return commissionInfo;
	}

	public static class ShopCommissionInfo {

		public String errCode;
		public String errInfo;
		public Boolean isSuccess;
		public Number totalResults;
		public List<ShopCommission> commissions = new ArrayList<ShopCommission>();
	}
	public static class ShopCommission{
		public Number user_id;
		public String shop_title;
		public String click_url;
		public String commission_rate;	
		public String seller_credit;
		public String shop_type;
		public String total_auction;
		public Number auction_count;		
		public String toString(){
			StringBuilder sb = new StringBuilder();
			sb.append("user_id:"+user_id);
			sb.append(";shop_title:"+shop_title);
			sb.append(";seller_credit:"+seller_credit);
			sb.append(";shop_type:"+shop_type);
			sb.append(";commission_rate:"+commission_rate);
			sb.append(";click_url:"+click_url);
			sb.append(";total_auction:"+total_auction);
			sb.append(";auction_count:"+auction_count);
			return sb.toString();
		}
	}
}
